package presentacion;

import javax.swing.JPanel;
import java.awt.GridBagLayout;
import javax.swing.JTable;
import java.awt.GridBagConstraints;

import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import java.awt.Insets;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;

import negocio.DirectorCurso;
import negocio.DirectorHorario;
import negocio.DirectorHorarioTiene;
import negocio.TransferDirector;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;

import com.jgoodies.forms.layout.ColumnSpec;



public class DirectorPanelHorario extends JPanel {
	private static final int HORA_INI = 9;
	private static final int INTERVALO = 30;
	private static final int NUM_INTERVALOS = 24;
	private JTable tableHorario;
	private JTextField textFieldIntervalo;
	private JTextField textFieldHoraIni;
	
	private int intervalos=30;
	private int horaIni=9;
	
	private ArrayList<String> horarioCursoSeleccionado;
	private DirectorHorarioTiene horarioActual;
	private ArrayList<DirectorCurso> listaCursos;
	private JComboBox<DirectorCurso> comboBoxCurso;
	private JButton btnEnviarHorario;
	private String palabraClaveHorario="s";
	
	private DirectorCurso cursoActual;

	/**
	 * Create the panel.
	 */
	public DirectorPanelHorario() {
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{659, 76, 57, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		JScrollPane scrollPane = new JScrollPane();
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.gridwidth = 3;
		gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 0;
		add(scrollPane, gbc_scrollPane);


		
		tableHorario = new JTable();
		tableHorario.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				if (tableHorario.getSelectedColumn()!=-1 && tableHorario.getSelectedRow()!=-1 && !tableHorario.getColumnName(tableHorario.getSelectedColumn()).equals("Hora") ){
					if (tableHorario.getValueAt(tableHorario.getSelectedRow(), tableHorario.getSelectedColumn())==""){
						if (comboBoxCurso.getSelectedItem()!=null)
						tableHorario.setValueAt(	cursoActual.toString(), tableHorario.getSelectedRow(), tableHorario.getSelectedColumn());
					}else{
						tableHorario.setValueAt("", tableHorario.getSelectedRow(), tableHorario.getSelectedColumn());
					}
				}
				
			}
		});
		scrollPane.setViewportView(tableHorario);
		tableHorario.setModel(new DefaultTableModel(
			new Object[][] {
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
				{"", "", "", "", "", "", "", ""},
			},
			new String[] {
				"Hora", "Lunes", "Martes", "Mi\u00E9rcoles", "Jueves", "Viernes", "S\u00E1bado", "Domingo"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, true, true, true, true, true, true
			};
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		});
		tableHorario.getColumnModel().getColumn(0).setMaxWidth(75);
		
		textFieldIntervalo = new JTextField();
		textFieldIntervalo.setEnabled(false);
		textFieldIntervalo.setEditable(false);
		GridBagConstraints gbc_textFieldIntervalo = new GridBagConstraints();
		gbc_textFieldIntervalo.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldIntervalo.insets = new Insets(0, 0, 5, 0);
		gbc_textFieldIntervalo.gridx = 2;
		gbc_textFieldIntervalo.gridy = 1;
		add(textFieldIntervalo, gbc_textFieldIntervalo);
		textFieldIntervalo.setColumns(10);
		
		textFieldHoraIni = new JTextField();
		textFieldHoraIni.setEditable(false);
		GridBagConstraints gbc_textFieldHoraIni = new GridBagConstraints();
		gbc_textFieldHoraIni.insets = new Insets(0, 0, 5, 0);
		gbc_textFieldHoraIni.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldHoraIni.gridx = 2;
		gbc_textFieldHoraIni.gridy = 2;
		add(textFieldHoraIni, gbc_textFieldHoraIni);
		textFieldHoraIni.setColumns(10);
		
		comboBoxCurso = new JComboBox();
		comboBoxCurso.addPopupMenuListener(new PopupMenuListener() {
			public void popupMenuCanceled(PopupMenuEvent arg0) {
			}
			public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
			}
			public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
				actualizarCBCursos();
			}
		});
		comboBoxCurso.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(comboBoxCurso.getSelectedIndex()!=-1){
					cursoActual=(DirectorCurso)comboBoxCurso.getSelectedItem();
					actualizarHorarioActual();
					if(horarioActual.getIdHorario()!=-1){
						actualizarHorarioDelCursoSeleccionado();
						actualizarTablaHorario();
					}
					
				}
				
				
				
			}
		});

		comboBoxCurso.setToolTipText("Curso");
		GridBagConstraints gbc_comboBoxCurso = new GridBagConstraints();
		gbc_comboBoxCurso.insets = new Insets(0, 0, 0, 5);
		gbc_comboBoxCurso.fill = GridBagConstraints.HORIZONTAL;
		gbc_comboBoxCurso.gridx = 0;
		gbc_comboBoxCurso.gridy = 3;
		add(comboBoxCurso, gbc_comboBoxCurso);
		
		btnEnviarHorario = new JButton("Enviar Horario");
		btnEnviarHorario.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				copiarContenidoTabla();
				insertaHorario();
				if(horarioActual.getIdHorario()!=-1){
					actualizarHorarioDelCursoSeleccionado();
					actualizarTablaHorario();
				}
			}

		});
		GridBagConstraints gbc_btnEnviarHorario = new GridBagConstraints();
		gbc_btnEnviarHorario.insets = new Insets(0, 0, 0, 5);
		gbc_btnEnviarHorario.gridx = 1;
		gbc_btnEnviarHorario.gridy = 3;
		add(btnEnviarHorario, gbc_btnEnviarHorario);
		
		//actualizar();
	}
	
	


	void actualizar(){
		actualizarTablaHorario();
	}


	void actualizarTablaHorario(){
		rellenarTablaHorario();
	}
	
	
	
	void actualizarCBCursos(){

		TransferDirector datos=new TransferDirector();
		SingletonControlador.getInstancia().evento(Evento.DIRECTOR_GET_LISTA_CURSOS, datos);
		
		//nos la guardamos para futuros usos
		listaCursos = datos.getListaCursos(); 
		
		DefaultComboBoxModel<DirectorCurso> dcm= (DefaultComboBoxModel<DirectorCurso>) comboBoxCurso.getModel();
		dcm.removeAllElements();
		
		for(Iterator<DirectorCurso> it = listaCursos.iterator();it.hasNext();){
			dcm.addElement(it.next());
		}
			
	}
	
	
	void actualizarHorarioDelCursoSeleccionado(){
			if(horarioActual==null) horarioActual=new DirectorHorarioTiene(null, -1);
			TransferDirector datos=new TransferDirector();
			datos.setHorario(horarioActual);
			if(horarioActual.getIdHorario()!=-1){
				SingletonControlador.getInstancia().evento(Evento.DIRECTOR_GET_HORARIO, datos);
				
				horarioActual=datos.getHorario();
			}
			
	}
	
	
	void insertaHorario(){
		TransferDirector datos=new TransferDirector();
		datos.setHorario(horarioActual);
		SingletonControlador.getInstancia().evento(Evento.DIRECTOR_INSERTA_HORARIO, datos);
		
	}
	
	
	
	void actualizarHorarioActual(){
		if(comboBoxCurso.getSelectedIndex()!=-1)
			horarioActual = new DirectorHorarioTiene(null,((DirectorCurso)comboBoxCurso.getSelectedItem()).getIdHorario());
		else 
			horarioActual = new DirectorHorarioTiene(null, -1);
	}
	
	
	
	
	
	//este copia de la tabla a un DirectorHorarioTiene
	private void copiarContenidoTabla() {
		actualizarHorarioActual();
		
		ArrayList<DirectorHorario> hT=new ArrayList<DirectorHorario>();
		for(int i=1;i<tableHorario.getColumnCount();i++) hT.add(crearHorarioDia(i));
		
		horarioActual.setHorarioTiene(hT);
		
	}
	
	
	private DirectorHorario crearHorarioDia(int dia){
		int horaIni=-1;
		int horaFin=-1;
		int minIni=-1;
		int minFin=-1;
		DefaultTableModel dtm = (DefaultTableModel) tableHorario.getModel();
		String diaSemana = dtm.getColumnName(dia);
		ArrayList<Integer> horas = generaIntervalosInt(this.horaIni, intervalos);
		for(int i=0;i<dtm.getRowCount();i++){
			if(dtm.getValueAt(i, dia)!=""){
				if(horaIni==-1/*&&horas.get(i)>=(i/2+this.horaIni)*60*/) {//si es el primero ocupado
					horaIni=horas.get(i)/60;
					minIni=horas.get(i)%60;
				}
				//vamos actualizando para dejarlos en el ultimo 
				if(horaIni!=-1){
					horaFin=(horas.get(i)+30)/60;
					minFin=(horas.get(i)+30);
					minFin=minFin%60;
				}
			}
		}
		
		
		DirectorHorario h = new DirectorHorario(horaIni, horaFin, minIni, minFin, horarioActual.getIdHorario(), diaSemana);
		return h;
	}
	
	
	
	
	
	
	//Para hacer la tablita
	
	//horaini e intervalo validos
	ArrayList<String> generaIntervalos(int horaIni,int intervalo){
		ArrayList<String> intervalos=new ArrayList<String>();
		if(horaIni>=0 && intervalo>0){
			for(int i=0;i<NUM_INTERVALOS;i++){
				int h1,h2,m1,m2;
				h1=horaIni+(intervalo*i)/60;
				h2=horaIni+(intervalo*(i+1))/60;
				m1=(intervalo*i)%60;
				m2=(intervalo*(i+1))%60;
				String s=h1+":"+m1+"-"+h2+":"+m2;
				intervalos.add(s);
			}
		}
		return intervalos;
	}
	
	
	//horaini e intervalo validos
	ArrayList<Integer> generaIntervalosInt(int horaIni,int intervalo){
		ArrayList<Integer> intervalos=new ArrayList<Integer>();
		if(horaIni>=0 && intervalo>0){
			for(int i=0;i<=tableHorario.getRowCount();i++){
				int h1,h2,m1,m2;
				h1=horaIni+(intervalo*i)/60;
				//h2=horaIni+(intervalo*(i+1))/60;
				m1=(intervalo*i)%60;
				//m2=(intervalo*(i+1))%60;
				Integer s=new Integer(h1*60+m1);
				intervalos.add(s);
			}
		}
		return intervalos;
	}
	
	//horaini e intervalo validos
	ArrayList<ArrayList<String>> generaContenidoParcial(DirectorHorarioTiene horario,int horaIni, int intervalo){
		
		
		if(horario!=null){
			ArrayList<ArrayList<String>> contenidoParcial= new ArrayList<ArrayList<String>>();
			
			for(Iterator<DirectorHorario> it= horario.getHorarioTiene().iterator();it.hasNext();){
				ArrayList<String> horarioDia = new ArrayList<String>();
				DirectorHorario dh = it.next();
				
				int tIni=(dh.getHoraIni()*60)+dh.getMinIni();
				int tFin=(dh.getHoraFin()*60)+dh.getMinFin();
				
				ArrayList<Integer> it2=generaIntervalosInt(horaIni,intervalo);
				int i=0;
				while(i<it2.size()){
					int margenInf=it2.get(i).intValue();
					int margenSup=margenInf+intervalo;
					if((tIni>=margenInf&&tIni<margenSup)||(tFin<=margenSup&&tFin>margenInf)||(tIni<margenInf&&tFin>margenSup)) horarioDia.add(cursoActual.toString());
					else horarioDia.add("");
					i++;
				}
				
				horarioDia.add(0, dh.getDiaSemana());
				
				contenidoParcial.add(horarioDia);
				
				
			}
			
			return contenidoParcial;
		}
		
		return null;
		
		
	}

	
	void rellenarTablaHorario(){
		DefaultTableModel dtm = (DefaultTableModel) tableHorario.getModel();
		DefaultTableModel dtm2 = new DefaultTableModel();;
		//dtm.setColumnCount(0);
		//dtm.setRowCount(0);
		
		
		try {
			if(textFieldHoraIni.getText()!=null && textFieldIntervalo.getText()!=null){
				intervalos=Integer.valueOf(textFieldIntervalo.getText())/60;
				horaIni=Integer.valueOf(textFieldHoraIni.getText())/24;
			}
		} catch (NumberFormatException e) {
			intervalos=INTERVALO;
			horaIni=HORA_INI;
		}
		if(horarioActual!=null){
			ArrayList<String> rowHeader=generaIntervalos(horaIni,intervalos);
			ArrayList<ArrayList<String>> contenidoHorario=new ArrayList<ArrayList<String>>();
			
			rowHeader.add(0,dtm.getColumnName(0));
			contenidoHorario.add(0,rowHeader);
			
			//Borrar columnas es una....
			//TableColumnModel tcm = (TableColumnModel) tableHorario.getModel();
			//tcm.removeColumn(tcm.getColumn(0));
			//dtm.addColumn("Hora", rowHeader.toArray());
		

			
			ArrayList<ArrayList<String>> restoContenido=generaContenidoParcial(horarioActual, horaIni, intervalos);
			contenidoHorario.addAll(restoContenido);
			Iterator<ArrayList<String>> it = contenidoHorario.iterator();
			int[] vacio = {1,1,1,1,1,1,1,1};
			while(it.hasNext()){
				ArrayList<String> actual=it.next();
				String nombreCol=actual.get(0);//cabecera
				actual.remove(0);//cabecera
				
				Collator c = Collator.getInstance();
				c.setStrength(Collator.PRIMARY);
				for(int i=0;i<dtm.getColumnCount();i++){
					if(0==c.compare(nombreCol, dtm.getColumnName(i))){
						for(int j=0;j<NUM_INTERVALOS;j++) {
							dtm.setValueAt(actual.get(j), j, i);
							
						}
						vacio[i]=0;
					}else 
						vacio[i]=vacio[i]*1;
				}
				
					
					
				//contenidoHorario.add(actual);
				//dtm.addColumn(nombreCol,actual.toArray());
				
				

			}
			for(int i=0;i<vacio.length;i++)
				if(vacio[i]!=0)
					for(int j=0;j<NUM_INTERVALOS;j++) 
						dtm.setValueAt("", j, i );
				
		
		
			
		}
		
		
		
		
		
		
	}
}